use crate::models::customer_groups::{self, CreateParams, UpdateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/customer-groups", post(create))
        .route("/customer-groups/:id", get(get_by_id))
        .route("/customer-groups/:id", post(update))
        .route("/customer-groups/:id/delete", post(delete))
        .route("/customer-groups/by-level/:level", get(get_by_level))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let group = customer_groups::Model::create(&state.db, params).await?;
    format::json(group)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let group = customer_groups::Model::find_by_id(&state.db, &id).await?;
    format::json(group)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<UpdateParams>,
) -> Result<Response> {
    let group = customer_groups::Model::update_by_id(&state.db, &id, params).await?;
    format::json(group)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    customer_groups::Model::delete_by_id(&state.db, &id).await?;
    format::json(())
}

async fn get_by_level(
    State(state): State<AppContext>,
    axum::extract::Path(level): axum::extract::Path<i32>,
) -> Result<Response> {
    let group = customer_groups::Model::find_by_level(&state.db, level).await?;
    format::json(group)
}
